package com.zk.config.web.util;

import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.server.auth.DigestAuthenticationProvider;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.zk.config.web.model.User;
import com.zk.config.web.model.ZkPerms;

@Component
public class Permiss {
	private static final Logger logger = org.slf4j.LoggerFactory.getLogger(Permiss.class);
	public static Map<Integer, Integer> roles = new HashMap<Integer, Integer>(){{
		put(1, ZooDefs.Perms.ALL);
		put(2, ZooDefs.Perms.READ);
		}};
 
	public List<ACL> getACLList() {
		List<ACL> acls = new ArrayList<ACL>();
		HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String userName = (String)req.getSession().getAttribute(AuthUtils.ZK_USER);
		if (userName != null) {
			User user = AuthUtils.userInfo.get(userName);
			if(user != null && roles.containsKey(user.getRole()) && user.getRole() == 1) {
				try {
					Id id = new Id("digest", DigestAuthenticationProvider.generateDigest(userName+":"+user.getPassword()));
					ACL acl = new ACL(roles.get(user.getRole()), id);
					acls.add(acl);
				} catch (NoSuchAlgorithmException e) {
					e.printStackTrace();
					logger.error(e.getMessage());
				}
			}
		}
			
		for(String key:AuthUtils.userInfo.keySet()) {
			User user = AuthUtils.userInfo.get(key);
			if (user != null) {
				try {
					Id id = new Id("digest", DigestAuthenticationProvider.generateDigest(user.getName()+":"+user.getPassword()));
					if(roles.containsKey(user.getRole())) {
						if(user.getRole() != 1) {
							ACL acl = new ACL(roles.get(user.getRole()), id);
							acls.add(acl);
						} else if(!key.equals(userName)) {
							ACL acl = new ACL(roles.get(2), id);
							acls.add(acl);
						}
					}
				} catch (NoSuchAlgorithmException e) {
					e.printStackTrace();
					logger.error(e.getMessage());
				}
			}
		}
		
		return acls;
	}
	
	public static List<ZkPerms> getPerms(ZooKeeper zk, String path) {
		List<ZkPerms> permsList = null;
		try {
			List<ACL> acls = zk.getACL(path, null);
			if(acls != null) {
				permsList = new ArrayList<>();
				for(ACL acl:acls) {
					if(acl == null || acl.getId() == null) continue;
					ZkPerms zkPerms = new ZkPerms();
					String id = acl.getId().toString();
					if(id != null) {
						int index = id.lastIndexOf("'");
						if(index != -1) {
							String[] parts = id.substring(index+1).split(":");
							zkPerms.setUser(parts[0]);
						}
					}
					
					if(ZooDefs.Perms.ALL == acl.getPerms()) {
						zkPerms.setPerms("ALL");
					} else if(ZooDefs.Perms.ADMIN == acl.getPerms()) {
						zkPerms.setPerms("ADMIN");
					} else if(ZooDefs.Perms.CREATE == acl.getPerms()) {
						zkPerms.setPerms("CREATE");
					} else if(ZooDefs.Perms.DELETE == acl.getPerms()) {
						zkPerms.setPerms("DELETE");
					} else if(ZooDefs.Perms.READ == acl.getPerms()) {
						zkPerms.setPerms("READ");
					} else if(ZooDefs.Perms.WRITE == acl.getPerms()) {
						zkPerms.setPerms("WRITE");
					} else {
						continue;
					}
					permsList.add(zkPerms);
				}
			}
		} catch (KeeperException e1) {
			e1.printStackTrace();
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
		
		return permsList;
	}
}
